import java.util.Stack;

public class Solution20 {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!stack.empty()) {
                char top = stack.peek();
                if ((c == ')' && top == '(') || (c == ']' && top == '[' || (c == '}' && top == '{')))
                    stack.pop();
                else
                    stack.push(c);
            } else {
                stack.push(c);
            }
        }
        return stack.empty();
    }
}
